<template>
  <div class="cart-container">
    <el-card class="cart-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold;">我的购物车</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="clearCart">清空购物车</el-button>
      </div>

      <el-table :data="cartList" style="width: 100%" @selection-change="handleSelectionChange" ref="cartTable">
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="商品信息" width="400">
          <template slot-scope="scope">
            <div class="product-info">
              <el-image :src="getImageUrl(scope.row.product.imageId)" fit="contain"
                style="width: 80px; height: 80px; margin-right: 15px;"></el-image>
              <div class="product-details">
                <div class="product-name">{{ scope.row.product.name }}</div>
                <!-- <div class="product-spec">{{ scope.row.specification }}</div> -->
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单价" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.product.price.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="180">
          <template slot-scope="scope">
            <div class="quantity-control">
              <el-button size="mini" :disabled="scope.row.quantity <= 1"
                @click="decreaseQuantity(scope.row)">-</el-button>
              <!-- <el-input v-model="scope.row.quantity" :min="1" :max="99" size="mini" controls-position="right"
                @change="handleQuantityChange(scope.row)"></el-input> -->
              <div style="margin: 0 10px;"> {{ scope.row.quantity }}</div>
              <el-button size="mini" :disabled="scope.row.quantity >= 99"
                @click="increaseQuantity(scope.row)">+</el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="小计" width="120">
          <template slot-scope="scope">
            <span class="subtotal">¥{{ (scope.row.product.price * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="removeItem(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="selected-actions">
          <el-checkbox v-model="selectAll" @change="handleSelectAllChange">全选</el-checkbox>
          <!-- <el-button type="text" @click="removeSelected">删除选中</el-button> -->
        </div>
        <div class="checkout-section">
          <div class="total-info">
            <span>已选 {{ selectedItems.length }} 件商品</span>
            <span class="total-price">总价: <strong>¥{{ totalPrice.toFixed(2) }}</strong></span>
          </div>
          <el-button type="danger" size="medium" :disabled="selectedItems.length === 0"
            @click="showPaymentDialog">去结算</el-button>
        </div>
      </div>
    </el-card>

    <el-dialog title="支付确认" :visible.sync="paymentDialogVisible" width="30%" :before-close="handleClose">
      <div class="payment-content">
        <div class="payment-summary">
          <p>总共 <span class="highlight">{{ selectedItems.length }}</span> 件商品</p>
          <p>总价为 <span class="highlight">¥{{ totalPrice.toFixed(2) }}</span></p>
          <p class="password-tip">请输入密码进行支付</p>
        </div>

        <el-form :model="paymentForm" :rules="rules" ref="paymentForm">
          <el-form-item prop="address">
            <el-input v-model="paymentForm.address" type="text" placeholder="请填写地址"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="paymentForm.password" type="password" placeholder="请输入支付密码" show-password
              @keyup.enter.native="confirmPayment"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPayment">取消</el-button>
        <el-button type="primary" @click="confirmPayment" :loading="isPaying">确认支付</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import storage from '@/utils/storage'
export default {
  name: 'ShoppingCart',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入支付密码'));
      } else if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'));
      } else {
        callback();
      }
    };

    return {
      loginUser: null,
      paymentDialogVisible: false,
      paymentForm: {
        address: '',
        password: ''
      },
      isPaying: false,
      rules: {
        address: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || value.trim() === '') {
                callback(new Error('地址不能为空'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ]
      },
      userId: '',
      cartList: [

      ],
      selectedItems: [],
      selectAll: false,

    }
  },
  created() {
    this.paymentForm.address = storage.getLoginUser().address
    this.userId = storage.getLoginUser().id
    this.getCartList()
  },
  computed: {
    totalPrice() {
      console.log(this.selectedItems);

      return this.selectedItems.reduce((total, item) => {
        return total + (item.product.price * item.quantity)
      }, 0)
    }
  },
  methods: {
    showPaymentDialog() {
      this.paymentDialogVisible = true;
      // 重置表单
      this.$nextTick(() => {
        if (this.$refs.paymentForm) {
          this.$refs.paymentForm.resetFields();
        }
      });
    },
    // 关闭对话框前的处理
    handleClose(done) {
      if (this.isPaying) {
        this.$message.warning('正在处理支付，请稍候');
        return;
      }
      this.$confirm('确定要取消支付吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => { });
    },

    // 取消支付
    cancelPayment() {
      this.paymentDialogVisible = false;
      this.$message.info('已取消支付');
    },

    confirmPayment() {
      this.$refs.paymentForm.validate(valid => {
        if (valid) {
          const loginUser = storage.getLoginUser()
          if (loginUser.password !== this.paymentForm.password) {
            this.$message.error('支付密码错误');
          }

          this.$api.order.create(this.userId, this.paymentForm.address, this.selectedItems).then(res => {
            if (res.code === 200) {
              this.$message.success('支付成功');
              this.getCartList();
              this.paymentDialogVisible = false
            }
          })

        } else {
          return false;
        }
      });
    },

    getImageUrl(imageId) {
      return `http://localhost:8000/api/files/download/${imageId}`
    },
    getCartList() {
      this.$api.cart.list(this.userId).then(res => {
        if (res.code === 200) {
          this.cartList = res.data
        }
      })
    },
    // 增加数量
    increaseQuantity(item) {
      this.$api.cart.increase(this.userId, item.productId).then(res => {
        if (res.code === 200) {
          this.getCartList()
        }
      })

    },

    // 减少数量
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        this.$api.cart.decrease(this.userId, item.productId).then(res => {
          if (res.code === 200) {
            this.getCartList()
          }
        })
      }
    },

    // 数量改变
    handleQuantityChange(item) {
      this.updateCart()
    },

    // 删除单个商品
    removeItem(item) {
      this.$confirm('确定要删除该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.cart.remove(item.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getCartList()
          }
        })
      })
    },

    // 删除选中商品
    removeSelected() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请先选择要删除的商品')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedItems.length} 件商品吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedItems.forEach(selectedItem => {
          const index = this.cartList.findIndex(item => item.id === selectedItem.id)
          if (index !== -1) {
            this.cartList.splice(index, 1)
          }
        })
        this.selectedItems = []
        this.selectAll = false
        this.updateCart()
        this.$message.success('删除成功')
      })
    },

    // 清空购物车
    clearCart() {
      if (this.cartList.length === 0) {
        this.$message.warning('购物车已经是空的')
        return
      }

      this.$confirm('确定要清空购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.$api.cart.clear(this.userId).then(res => {
          if (res.code === 200) {
            this.$message.success('清空成功')
            this.getCartList()
          }
        })

      })
    },

    // 选择变化
    handleSelectionChange(items) {
      this.selectedItems = items
      this.selectAll = items.length === this.cartList.length && this.cartList.length > 0
    },

    // 全选/取消全选
    handleSelectAllChange(val) {
      if (val) {
        this.$refs.cartTable.toggleAllSelection()
      } else {
        this.$refs.cartTable.clearSelection()
      }
    },

    // 去结算
    checkout() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请选择要结算的商品')
        return
      }

      this.$router.push({
        path: '/order/checkout',
        query: {
          items: JSON.stringify(this.selectedItems)
        }
      })
    },

    // 更新购物车数据（实际项目中应该调用API）
    updateCart() {
      // 这里可以添加调用API更新购物车的逻辑
      console.log('购物车数据已更新', this.cartList)
    }
  }
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
  max-width: 100%;
  margin: 0 auto;
}

.cart-card {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.product-spec {
  font-size: 12px;
  color: #999;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-control .el-button {
  padding: 5px 10px;
}

.quantity-control .el-input-number {
  width: 100px;
  margin: 0 5px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.selected-actions {
  display: flex;
  align-items: center;
}

.selected-actions .el-checkbox {
  margin-right: 20px;
}

.checkout-section {
  display: flex;
  align-items: center;
}

.total-info {
  margin-right: 30px;
  text-align: right;
}

.total-price {
  display: block;
  font-size: 16px;
  margin-top: 5px;
}

.total-price strong {
  color: #f56c6c;
  font-size: 20px;
}






.payment-content {
  padding: 0 20px;
}

.payment-summary {
  margin-bottom: 20px;
  line-height: 1.8;
  font-size: 15px;
}

.payment-summary p {
  margin: 8px 0;
}

.highlight {
  color: #f56c6c;
  font-weight: bold;
}

.password-tip {
  margin-top: 15px !important;
  color: #666;
  font-size: 14px;
}

.dialog-footer {
  text-align: center;
}
</style>